package com.xuwei.base.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Test;

public class RegexMatches {
	/**
	 * 下面的例子说明如何从一个给定的字符串中找到数字串
	 * @param args
	 */
	@Test
	public void test01() {
		// 按指定模式在字符串查找
		String line = "This order was placed for QT3000! OK?";
		String pattern = "(.*)(\\d+)(.*)";

		// 创建 Pattern 对象
		Pattern r = Pattern.compile(pattern);

		// 现在创建 matcher 对象
		Matcher m = r.matcher(line);
		if (m.find()) {
			System.out.println("Found value: " + m.group(0));
			System.out.println("Found value: " + m.group(1));
			System.out.println("Found value: " + m.group(2));
		} else {
			System.out.println("NO MATCH");
		}
	}

	/**
	 * 下面是一个对单词"cat"出现在输入字符串中出现次数进行计数的例子
	 */
	@Test
	public void test02() {
		Pattern p = Pattern.compile("\\bcat\\b");
		Matcher m = p.matcher("cat cat cat cattie cat"); // 获取 matcher 对象
		int count = 0;

		while (m.find()) {
			count++;
			System.out.println("Match number " + count);
			System.out.println("start(): " + m.start());
			System.out.println("end(): " + m.end());
		}
	}

	/**
	 * matches 和lookingAt 方法都用来尝试匹配一个输入序列模式。
	 * 它们的不同是matcher要求整个序列都匹配，而lookingAt不要求
	 */
	@Test
	public void test03() {
		final String REGEX = "foo";
		final String INPUT = "foooooooooooooooooooooo";
		
		Pattern pattern = Pattern.compile(REGEX);
		Matcher matcher = pattern.matcher(INPUT);

		System.out.println("Current REGEX is: " + REGEX);
		System.out.println("Current INPUT is: " + INPUT);

		System.out.println("lookingAt(): " + matcher.lookingAt());
		System.out.println("matches(): " + matcher.matches());
	}
	
	/**
	 * replaceFirst 和replaceAll 方法用来替换匹配正则表达式的文本。不同的是，
	 * replaceFirst 替换首次匹配，replaceAll 替换所有匹配。
	 */
	@Test
	public void test04(){
		String regex = "dog";
		String input = "The dog says meow. All dogs say meow.";
		String replace = "cat";
		Pattern p = Pattern.compile(regex);
		//get a matcher object
		Matcher m = p.matcher(input);
		input = m.replaceAll(replace);
		System.out.println(input);
		
	}
	
	/**
	 * Matcher 类也提供了appendReplacement和appendTail 方法用于文本替换
	 */
	@Test
	public void test05(){
		String regex = "a*b";
		String input = "aabfooaabfooabfoob";
		String replace = "-";
		Pattern p = Pattern.compile(regex);
		//获取matcher对象
		Matcher m = p.matcher(input);
		StringBuffer sb = new StringBuffer();
		while(m.find()){
			m.appendReplacement(sb, replace);
		}
		m.appendTail(sb);   
		System.out.println(sb.toString());
	}
	
	
	
	
	

}